import requests
from bs4 import BeautifulSoup
import json
import time
import datetime


def get_domain_info(domain):
    url = 'http://whois.chinaz.com/{}'.format(domain)
    header = {'User-Agent': 'Mozilla/5.0'}
    result = {'Host': domain}
    domain_info_dict = {}
    try:
        r = requests.get(url, headers=header)
        r.raise_for_status()
        html = BeautifulSoup(r.text, 'lxml')
        domain_info = html.select('ul li.bor-b1s')
        # print(domain_info)
        for line in domain_info:
            line = line.text.strip().split('\n')
            # print(line)
            if line[0].startswith('注册商'):
                result['Registrar'] = line[0].strip('注册商')
            elif line[0].startswith('创建时间'):
                result['CreationDate'] = line[0].strip('创建时间').replace(
                    '年', '-').replace('月', '-').replace('日', 'T') + '00:00:00Z'
            elif line[0].startswith('过期时间'):
                result['ExpirationDate'] = line[0].strip('过期时间').replace(
                    '年', '-').replace('月', '-').replace('日', 'T') + '00:00:00Z'
            elif line[0].startswith('DNS'):
                result['DnsServer'] = line[0].strip('DNS').split()
            else:
                pass
        StateCode = 1
        Reason = 'success'
    except Exception as e:
        print(e)
        StateCode = 0
        Reason = 'failed'
    domain_info_dict['StateCode'] = StateCode
    domain_info_dict['Reason'] = Reason
    domain_info_dict['Result'] = result
    print(domain_info_dict)
    return domain_info_dict


# domain_list = ['xinidea.top', 'baidu.com', 'xindea.cn', '8z.net']
domain_list = ['xinidea.top']
for domain in domain_list:
    domain_info_dict = get_domain_info(domain)
    if domain_info_dict['StateCode']:
        d1 = datetime.datetime.strptime(
            domain_info_dict['Result']['ExpirationDate'], '%Y-%m-%d')
        d2 = datetime.datetime.now()
        delta = d1 - d2
        domain_info_dict['Result']['daysleft'] = delta.days
    print(json.dumps(domain_info_dict))
    time.sleep(2)
